/**
 * Created by no1 on 2015/8/7.
 */
'use strict';
let DD = require('./daoLoader');
let F = require('../function');
var Base = require('./Base');
var util = require("util");

let wareVersionDao = new DD.mongoDB.WareVersionDao();
let redisTest = new DD.redisDB.CategoryDao();
let addDays = function (date, day) {
  // 86400000 = 24*60*60*1000
  return new Date(date.getTime() + (86400000 * day))
}
function WareVersionDispatcher(data) {
  data = data || {};
  data.dao = data.dao || wareVersionDao;
  data.esDao = data.esDao || {};
  data.redisDao = data.redisDao || {};
  data.modelName = data.modelName || 'wareVersion';
  data.modelType = data.modelType || 'mongo';
  this.data = data;
  Base.call(this, this.data);

}
util.inherits(WareVersionDispatcher, Base);

/**
 * @todo 添加
 * @param fields
 * @returns {{error, msg, data}|{error, msg}}
 */
WareVersionDispatcher.prototype.add = function*(fields) {
  if (!fields.vendorid) F.returnData(1, '必须有vendorid');
  if (!fields.wareid) F.returnData(1, '必须有wareid');
  //验证商家id是否存在
  let venRet = yield F.getDataFromDispatcher('vendorDispatcher', 'getOneByQuery', {id: fields.vendorid});
  if (venRet.error == 1) return F.returnData(1, venRet.msg);

  let parameters = {}
    , arr = ['name', 'wareid', 'price', 'marketPrice', 'totalQuantity', 'images', 'newest', 'discount', 'reservation', 'onLineTime', 'offLineTtime', 'graphicDetails']
  for (let one of arr)if (!!fields[one]) parameters[one] = fields[one];
  parameters.vendorid = fields.vendorid;
  parameters.version = fields.version || 1;//版本
  parameters.status = 1;// 0删除 1 可以 2 删除审核中
  parameters.auditStatus = 1;// 1未审核 2审核通过 3审核不通过 4 审核中
  parameters.isSell = 0;//是否销售 0不销售

  //拼接带有loc shopInfo district 等参数的shops
  if (!!fields.shopids) {
    let shopsRet = yield F.getDataFromDispatcher('shopDispatcher', 'jointShopByids', fields.shopids, fields.vendorid);
    if (shopsRet.error == 1) return F.returnData(1, shopsRet.msg);
    parameters.shops = shopsRet.data || [];
  }
  //拼接category美容项目
  if (!!fields.cateCodes) {
    let retCate = yield F.getDataFromDispatcher('categoryDispatcher', 'jointCateByCodes', fields.cateCodes);
    if (retCate.error == 1) return F.returnData(1, retCate.msg);
    parameters.categories = retCate.data || [];
  }
  //拼接类别美容项目
  if (!!fields.serverCodes) {
    let retServices = yield F.getDataFromDispatcher('categoryDispatcher', 'jointSerByCodes', fields.serverCodes);
    if (retServices.error == 1) return F.returnData(1, retServices.msg);
    parameters.services = retServices.data;
  }
  let ret = yield this.dao.findAndSave({id: 0}, parameters);
  if (ret.error == 1) return F.returnData(1, ret.msg);
  return F.returnData(0, ret.msg, ret.data);
}

/**
 * @todo 更新
 * @param fields
 * @returns {{error, msg, data}|{error, msg}}
 */
WareVersionDispatcher.prototype.update = function*(fields) {
  if (!fields.id) return F.returnData(1, '必须有id');
  let parameters = {}
    , arr = ['name', 'price', 'marketPrice', 'totalQuantity', 'isSell', 'newest', 'images', 'discount', 'reservation', 'onLineTime', 'offLineTtime', 'submitTime', 'graphicDetails', 'status', 'auditStatus', 'deleteDescription']

  for (let one of arr)if (fields[one] != null) parameters[one] = fields[one];

  let retWV = yield this.dao.getByQuery({id: fields.id});
  if (retWV.error == 1 || retWV.data.length != 1) return F.returnData(1, '没有找到该商品版本');
  let WV = retWV.data[0];

  if (!!fields.wareid) {
    let retWare = yield F.getDataFromDispatcher('wareDispatcher', 'findByDis', {id: fields.wareid, status: 1});
    if (retWare.error == 1 || retWare.data.length != 1) return F.returnData(1, '没有找到该项目');
    if (WV.vendorid != retWare.data[0].vendorid) return F.returnData(1, '该项目的不属于同一商家');
    parameters.wareid = retWare.data[0].id;

  }

  //拼接带有loc shopInfo district 等参数的shops
  if (!!fields.shopids) {
    //let shopsRet = yield F.getDataFromDispatcher('shopDispatcher', 'jointShopByids', fields.shopids, fields.vendorid);
    let shopsRet = yield F.getDataFromDispatcher('shopDispatcher', 'jointShopByids', fields.shopids, WV.vendorid);
    if (shopsRet.error == 1) return F.returnData(1, shopsRet.msg);
    parameters.shops = shopsRet.data || [];
  }

  //拼接category美容项目
  if (!!fields.cateCodes) {
    let retCate = yield F.getDataFromDispatcher('categoryDispatcher', 'jointCateByCodes', fields.cateCodes);
    if (retCate.error == 1) return F.returnData(1, retCate.msg);
    parameters.categories = retCate.data || [];
  }
  //拼接类别美容项目
  if (!!fields.serverCodes) {
    let retServices = yield F.getDataFromDispatcher('categoryDispatcher', 'jointSerByCodes', fields.serverCodes);
    if (retServices.error == 1) return F.returnData(1, retServices.msg);
    parameters.services = retServices.data || [];
  }
  if (!!fields.auditLog && !!fields.auditLog.auditStatus && !!fields.auditLog.comment) {
    parameters['$push'] = {
      auditLog: {
        auditStatus: fields.auditLog.auditStatus || 1,
        comment: fields.auditLog.comment || ''
      }
    }
  }

  let ret = yield this.dao.findAndUpdate({id: fields.id}, parameters);
  if (ret.error == 1) return F.returnData(1, ret.msg);
  return F.returnData(0, ret.msg, ret.data);
}

/**
 * @todo 列表
 * @param fields
 * @returns {{error, msg, data}|{error, msg}}
 */
WareVersionDispatcher.prototype.list = function*(fields) {
  let parameters = {}, opt = {}, retData = {}
    , arrDel = ['_id', '__v', '__t'], isSort = {id: -1}
    , isPaging = fields.isPaging || 0
    , page = fields.page || 1
    , pageSize = fields.pageSize || 50
    , retDataList, retCount, count, arr
  //默认列表
  if (fields.act == 1) {
    for (let one of arrDel) opt[one] = 0;
    let ret = yield this.dao.getByQueryPor(parameters, opt, {page: page, pageSize: pageSize}, {id: -1});
    if (ret.error == 1) return F.returnData(1, ret.msg, ret.data);
    let json = JSON.parse(JSON.stringify(ret.data));
    let retData = F.dataFilter(json, ['_id']);
    return F.returnData(0, ret.msg, retData);
  }
  // 商家详情中的项目列表
  else if (fields.act == 2) {
    if (!fields.vendorid) return F.returnData(1, '必须有商家id');
    let arr = ['id', 'name', 'wareid', 'vendorid', 'price', 'totalQuantity', 'auditStatus', 'onLineTime', 'offLineTtime', 'status', 'isSell', 'version']
    for (let one of arr) opt[one] = 1;
    parameters.vendorid = fields.vendorid;
    parameters.newest = 1;

    let retWV = yield this.dao.getByQueryPor(parameters, opt, {page: page, pageSize: pageSize}, isSort)
    if (retWV.error == 1) return F.returnData(1, retWV.msg, retWV.data);
    retDataList = retWV.data;

    let retCount = yield this.dao.getCountByQuery(parameters);
    if (retCount.error == 1) return F.returnData(1, retCount.msg, retCount.data);
    count = retCount.data;

    //查询在线商品
    let wareids = [];
    for (let one of retDataList) {
      if (one.wareid != undefined) wareids.push(one.wareid);
    }
    let retWare = yield F.getDataFromDispatcher('wareDispatcher', 'findByDis', {id: {$in: wareids}});
    if (retWare.error == 1) return F.returnData(1, retWare.msg);

    //合并数据
    let tmp = []
    for (let one of retDataList) {
      for (let ware of retWare.data) {
        if (one.wareid == ware.id) {
          one.totalQuantity = ware.totalQuantity;
          one.buyNumber = ware.buyNumber
          break;
        }
      }
      tmp.push(one);
    }
    retDataList = tmp;
    let json = JSON.parse(JSON.stringify(retDataList));
    retDataList = F.dataFilter(json, ['_id']);
    //拼接返回数据结构
    if (isPaging == 1) {
      retData.list = retDataList;
      retData.count = count;
    }
    else retData = retDataList;
    return F.returnData(0, retWV.msg, retData);
  }
  //项目审核中的最新列表
  else if (fields.act == 3) {
    let arr = ['id', 'name', 'wareid', 'vendorid', 'submitTime', 'status', 'version', 'auditStatus']
    for (let one of arr) opt[one] = 1;
    parameters.newest = 1;
    if (!!fields.query) {
      fields.query || (fields.query = "");
      let str = fields.query.replace(/[\+]*[\*]*[\?]*[\$]*[\^]*[\\]*/g, '');
      str = str.split('').join('+[\\s\\S]*');
      let re = new RegExp(str, 'i');
      parameters.name = {$regex: re};
    }
    if (fields.auditStatus != null) parameters.auditStatus = fields.auditStatus;
    if (fields.submitTime != null) {
      let submitTime = fields.submitTime
      let start = new Date(submitTime);
      let end = addDays(start, 1);
      parameters.submitTime = {$gte: start, $lt: end};
      isSort = {submitTime: -1};
    }
    let retWV = yield this.dao.getByQueryPor(parameters, opt, {page: page, pageSize: pageSize}, isSort)
    if (retWV.error == 1) return F.returnData(1, retWV.msg, retWV.data);
    retDataList = retWV.data;
    let retCount = yield this.dao.getCountByQuery(parameters);
    if (retCount.error == 1) return F.returnData(1, retCount.msg, retCount.data);
    count = retCount.data;
    //查询项目对应的商家
    let vendorids = [];
    for (let one of retDataList) if (!!one.vendorid && vendorids.indexOf(one.vendorid) == -1) vendorids.push(one.vendorid);
    let retVendorList = yield F.getDataFromDispatcher('vendorDispatcher', 'findByDis', {id: {$in: vendorids}});
    if (retVendorList.error == 1) return F.returnData(1, retVendorList.msg);
    //合并数据
    let tmp = []
    for (let one of retDataList) {
      for (let vendor of retVendorList.data) {
        if (one.vendorid == vendor.id) {
          one.vendorName = vendor.name;
          break;
        }
      }
      tmp.push(one);
    }
    retDataList = tmp;
    //buyNumber
    let json = JSON.parse(JSON.stringify(retDataList));
    retDataList = F.dataFilter(json, ['_id']);
    //拼接返回数据结构
    if (isPaging == 1) {
      retData.list = retDataList;
      retData.count = count;
    }
    else retData = retDataList;

    return F.returnData(0, retWV.msg, retData);
  }
  //后台查询历史版本
  else if (fields.act == 4) {
    if (!fields.wareid) return F.returnData(1, '必须有项目id');
    let arr = ['id', 'name', 'wareid', 'vendorid', 'submitTime', 'status', 'version']
    for (let one of arr) opt[one] = 1;
    parameters.wareid = fields.wareid;

    let retWV = yield this.dao.getByQueryPor(parameters, opt, {page: page, pageSize: pageSize}, isSort)
    if (retWV.error == 1) return F.returnData(1, retWV.msg, retWV.data);
    retDataList = retWV.data;
    let retCount = yield this.dao.getCountByQuery(parameters);
    if (retCount.error == 1) return F.returnData(1, retCount.msg, retCount.data);
    count = retCount.data;
    //查询项目对应的商家
    let vendorid = retDataList[0].vendorid;
    let retVendor = yield F.getDataFromDispatcher('vendorDispatcher', 'findByDis', {id: vendorid});
    if (retVendor.error == 1) return F.returnData(1, retVendor.msg);
    //合并数据
    for (let i in retDataList) retDataList[i].vendorName = retVendor.data[0].name || '';
    let json = JSON.parse(JSON.stringify(retDataList));
    retDataList = F.dataFilter(json, ['_id']);
    //拼接返回数据结构
    if (isPaging == 1) {
      retData.list = retDataList;
      retData.count = count;
    }
    else retData = retDataList;
    return F.returnData(0, retWV.msg, retData);
  }
  //总后台删除管理中的项目删除
  else if (fields.act == 5) {
    //拼接查询条件
    if (fields.query != null) {
      let str = fields.query.replace(/[\+]*[\*]*[\?]*[\$]*[\^]*[\\]*/g, '')
      str = str.split('').join('+[\\s\\S]*');
      let re = new RegExp(str, 'i');
      parameters.name = {$regex: re};
    }
    if (fields.submitTime != null) {
      let submitTime = fields.submitTime
      let start = new Date(submitTime);
      let end = F.addDays(start, 1);
      parameters.submitTime = {$gte: start, $lt: end};
      isSort = {submitTime: -1};
    }
    parameters.status = (fields.status == null) ? 2 : fields.status;
    //提取数据
    arr = ['id', 'name', 'vendorid', 'submitTime', 'status', 'deleteDescription'];
    for (let one of arr) opt[one] = 1;
    //查询项目版本
    let ret = yield this.dao.getByQueryPor(parameters, opt, {page: page, pageSize: pageSize}, isSort);
    if (ret.error == 1) return F.returnData(1, ret.msg);
    retDataList = ret.data;
    //查询项目对应的商家
    let vendorids = [];
    for (let one of retDataList) if (!!one.vendorid && vendorids.indexOf(one.vendorid) == -1) vendorids.push(one.vendorid);
    let retVendorList = yield F.getDataFromDispatcher('vendorDispatcher', 'findByDis', {id: {$in: vendorids}});
    if (retVendorList.error == 1) return F.returnData(1, retVendorList.msg);
    //拼接数据
    for (let one of retDataList) {
      for (let vendor of retVendorList.data) {
        if (one.vendorid == vendor.id) {
          one.vendorName = vendor.name;
          break;
        }
      }
    }
    //过滤数据
    let json = JSON.parse(JSON.stringify(retDataList));
    retDataList = F.dataFilter(json, ['_id']);
    //返回数据
    if (isPaging == 1) {
      retCount = yield this.dao.getCountByQuery(parameters);
      retData.list = retDataList;
      retData.count = retCount.data;
    } else retData = retDataList
    return F.returnData(0, 'ok', retData);
  }
}

/**
 * @todo 获取详情
 * @param fields
 * @returns {{error, msg, data}|{error, msg}}
 */
WareVersionDispatcher.prototype.detail = function*(fields) {
  if (!fields.id) return F.returnData(1, '必须有id');

  //排除不必要的字段
  let opt = {}
    , ret = {}
    , retData
  let arrDel = ['_id', 'otherInfo', '__v', '__t', 'shops.shopInfo', 'ts']
  if (fields.act == 1) {
    for (let one of arrDel) opt[one] = 0;
    //查询
    ret = yield this.dao.getOneByQuery({id: fields.id}, opt);
    if (ret.error == 1) return F.returnData(1, ret.msg);
  }
  //过滤数据
  let json = JSON.parse(JSON.stringify(ret.data));
  retData = F.dataFilter(json, ['_id']);
  return F.returnData(0, ret.msg, retData);
}
/**
 * 内部调用
 * @param Que
 * @returns {{error, msg, data}|{error, msg}}
 */
WareVersionDispatcher.prototype.findByDis = function*(Que) {
  let arrDel = ['_id', '__v', '__t', 'createdAt', 'updateAt']
    , opt = {};
  for (let one of arrDel) opt[one] = 0;
  let ret = yield this.dao.getByQuery(Que, opt);
  if (ret.error == 1) F.returnData(1, ret.msg, ret.data);
  return F.returnData(0, ret.msg, ret.data);
}
module.exports = WareVersionDispatcher;